local clientui = require 'ui.client.util'
local serverui = require 'ui.server.util'
local dbg = require 'jass.debug'
local storm = require 'jass.storm'

local function update_exit_flag()
    storm.save("file.txt", "1")
end 

-- 检查异步的间隔
local check_time = 10 * 1000
local function check_data(data)
    local self_data = data[ac.player.self.id]
    local flag
    for i = 1, 8 do
        if ac.player[i]:is_player() then
            data[i] = self_data == data[i]
            if not data[i] then
                local msg = '自动异步检测-'.. ac.player[i]:get_name()..' 已异步'
                ac.player.self:send_msg(msg)
                print(msg)
                ac.player[i].has_async = true
                flag = true

                update_exit_flag()
            end
        end
    end
    if not flag then
        print('自动异步检测-正常')
    end
end

ac.wait(2000, function ()
    if ac.player.count < 2 then 
        return 
    end
    local datas = {}
    local c = function()
        for i = 1, 8 do
            if ac.player[i]:is_player() and not datas[i] then
                return
            end
        end
        check_data(datas)
        datas = {} --清空统计
    end
    ac.game:event '玩家-离开'(c)
    serverui.register_event('asyc_check', {
        ['handle_data'] = function(id, data, t)
            datas[id] = data
            c()
        end
    })
    ac.loop(check_time, function(timer) 
        if ac.player.count < 2 then 
            timer:remove() 
            return 
        end
        clientui.send_message({
            type = 'asyc_check',
            func_name = 'handle_data', -- 发送到服务端 
            params = {
                ac.player.self.id,
                dbg.handlecount(),
                ac.clock()
            }
        },true)
    end)
end)